class ApplicationController < ActionController::Base
  helper :all 
  protect_from_forgery

  helper_method :current_user,:last_day_of_month 

  private
   def current_user_session
    return @current_user_session if defined?(@current_user_session)
      @current_user_session = UserSession.find
    end

   def current_user
     @current_user = current_user_session && current_user_session.record
   end

	  def require_any_user
	     unless current_user
	       flash[:notice] = "Usted requiere iniciar sesión en el sistema para ver esta sección"
	       redirect_to :controller => "login"
	       return false
	     end
      #this is because we need reusing code ( see require_admin => require_pharmacist )
       return true
	 end

     def not_user_required
	     unless current_user.nil?
	       redirect_to :controller => "welcome"
	       return false
	     end
       return true
     end


     def require_admin
       if require_any_user==true
        unless (current_user.role_id==1)
           flash[:notice] = "Usted requiere privilegios especiales para estar aquí"
           redirect_to :controller => "restriction"
           return false
        end
        return true
      end
    end

    def require_project_manager
      if require_any_user==true
       unless ( current_user.role_id==2 || current_user.role_id==1)
         flash[:notice] = "Usted requiere privilegios especiales para estar aquí"
	       redirect_to :controller => "restriction"
	       return false
	     end
       return true
     end
    end


    def require_team_member
      if require_any_user==true
       unless ( current_user.role_id==3 || current_user.role_id==1)
         flash[:notice] = "Usted requiere privilegios especiales para estar aquí"
	       redirect_to :controller => "restriction"
	       return false
	     end
       return true
     end
    end

   def last_day_of_month yyyy, mm
     d = Date.new(yyyy, mm)                        # no day means the first one
     d += 42                                 # always the next month
     Date.new(d.year, d.month) - 1
   end

end
